/**
 * Created by Marko on 3/30/14.
 */

$(document).ready(function() {

    // error handler

    function showError(xhr, textStatus, errorThrown) {
                    //enable add button
                    $(formbutton).removeAttr("disabled");
                    $(formToSubmit + ' #status_info').html(alert_html('Error ocured...\n' + xhr + '\n' + textStatus + errorThrown + '\n', 'error'));
    }

    // pre-submit callback 
    function showRequest(formData, jqForm, options) { 
        // formData is an array; here we use $.param to convert it to a string to display it 
        // but the form plugin does this for you automatically when it submits the data 
        var queryString = $.param(formData); 
     
        // jqForm is a jQuery object encapsulating the form element.  To access the 
        // DOM element for the form do this: 
        // var formElement = jqForm[0]; 
     
        alert('About to submit: \n\n' + queryString); 
     
        // here we could return false to prevent the form from being submitted; 
        // returning anything other than false will allow the form submit to continue 
        return true; 
    }
     
    // post-submit callback 
    function showResponse(data, textStatus, xhr)  {

                    if (data.action == true) {

                        var n = noty(
                            {
                                text: localizedStrings['changesSaved'][locale] + '\n' + data.msg,
                                layout: 'bottomLeft',
                                type: 'success'

                            });

                        function action_delay() {
                            window.location.reload();
                        }

                        window.setTimeout(function() {
                            action_delay();
                        }, 2001);

                    } else {

                        $(formbutton).removeAttr("disabled");

                        var n = noty(
                            {
                                text: localizedStrings['error'][locale] + '\n' + data.msg,
                                layout: 'bottomLeft',
                                type: 'error'

                            });

                        $(formToSubmit).animate({
                            scrollTop: $(formToSubmit + ' .status_info').offset().top
                        }, 200);
                    }
    } 

    var formToSubmit = '#picture_form';
    var formbutton = '#submit_form';


    var options = { 
        target:        '#output2',   // target element(s) to be updated with server response 
        beforeSubmit:  showRequest,  // pre-submit callback 
        success:       showResponse,  // post-submit callback 
        dataType: 'json',
        error: showError
 
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 


    // Add method to jQuery validator
    $.validator.addMethod('positive_non_zero',
        function(value) {

            return Number(value) > 0;
        });


    //FORM VALIDATION
    jQuery(formToSubmit).validate({
        rules: {
            name: 'required',
            alt: 'required'

        },
        highlight: function(element) {
            $(element).addClass("error");
        },
        unhighlight: function(element) {
            $(element).removeClass("error");
        },
        submitHandler: function(form) {
        var ext = $('#picture').val().split('.').pop().toLowerCase();
        if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
            var message = 'Invalid file extension! Valid file formats art [gif, png, jpg, jpeg]';
            $('#status_info').html('<div class="alert alert-error"><a href="#" class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')
            return;
        }

            //disable add button
            $(formbutton).attr("disabled", "disabled");

            var form = $(formToSubmit);

            // submit form using jquery ajax form submission plugin
            $(form).ajaxSubmit(options); 

        },
        errorPlacement: function(error, element) {
        }
    });

    $(formbutton).removeAttr("disabled");



})